using Microsoft.Extensions.DependencyInjection;
using ORS.OrderRobot.Cache;
using ORS.OrderRobot.Queue;
using StackExchange.Redis;

namespace ORS.OrderRobot
{
    public static class ServiceCollectionExtensions
    {
        /// <summary>
        /// 添加Redis服务
        /// </summary>
        /// <param name="services">服务集合</param>
        /// <param name="configure">Redis配置选项</param>
        /// <returns>服务集合</returns>
        public static IServiceCollection AddRedisServices(
            this IServiceCollection services,
            Action<RedisOptions> configure)
        {
            var options = new RedisOptions();
            configure(options);

            // 注册Redis配置选项
            services.AddSingleton(options);

            // 注册Redis连接
            services.AddSingleton<IConnectionMultiplexer>(sp => 
            {
                var configOptions = new ConfigurationOptions
                {
                    EndPoints = { options.ConnectionString },
                    DefaultDatabase = options.DefaultDatabase,
                    ConnectTimeout = options.ConnectTimeout * 1000,
                    SyncTimeout = options.SyncTimeout * 1000,
                    Ssl = options.UseSsl
                };

                if (!string.IsNullOrEmpty(options.Password))
                {
                    configOptions.Password = options.Password;
                }

                return ConnectionMultiplexer.Connect(configOptions);
            });

            // 注册Redis缓存
            services.AddSingleton<ICache, RedisCache>();

            // 注册Redis消息队列
            services.AddSingleton(typeof(IMessageQueue<>), typeof(RedisMessageQueue<>));

            return services;
        }
    }
} 